package com.property.demo.controller;

import com.property.demo.dto.ApiResponse;
import com.property.demo.dto.HomeDTO;
import com.property.demo.model.Home;
import com.property.demo.model.Building;
import com.property.demo.model.Owner;
import com.property.demo.repository.HomeRepository;
import com.property.demo.repository.BuildingRepository;
import com.property.demo.repository.OwnerRepository;
import com.property.demo.service.HomeService;
import com.property.demo.util.DTOMapper;
import com.property.demo.util.SortUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/homes")
public class HomeController {

    @Autowired
    private HomeRepository homeRepository;
    
    @Autowired
    private BuildingRepository buildingRepository;
    
    @Autowired
    private OwnerRepository ownerRepository;
    
    @Autowired
    private HomeService homeService;

    // 获取所有房产（分页）
    @GetMapping
    public ResponseEntity<?> getAllHomes(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(required = false) Long buildingId,
            @RequestParam(required = false) Long ownerId,
            @RequestParam(required = false) String name,
            @RequestParam(required = false) String status,
            @RequestParam(defaultValue = "id,desc") String[] sort) {
        
        try {
            List<Sort.Order> orders = SortUtil.getOrders(sort);
            Pageable pageable = PageRequest.of(page, size, Sort.by(orders));
            
            Page<Home> homesPage;
            if (buildingId != null || ownerId != null || (name != null && !name.isEmpty()) || (status != null && !status.isEmpty())) {
                homesPage = homeService.findByFilters(buildingId, ownerId, name, status, pageable);
            } else {
                homesPage = homeService.findAll(pageable);
            }
            
            List<HomeDTO> homeDTOs = homesPage.getContent().stream()
                    .map(DTOMapper::toHomeDTO)
                    .collect(Collectors.toList());
            
            Map<String, Object> response = new HashMap<>();
            response.put("content", homeDTOs);
            response.put("currentPage", homesPage.getNumber());
            response.put("totalItems", homesPage.getTotalElements());
            response.put("totalPages", homesPage.getTotalPages());
            
            return new ResponseEntity<>(response, HttpStatus.OK);
        } catch (Exception e) {
            return new ResponseEntity<>(
                new ApiResponse(false, "获取房产列表失败: " + e.getMessage()),
                HttpStatus.INTERNAL_SERVER_ERROR
            );
        }
    }

    // 获取所有房产（不分页）
    @GetMapping("/all")
    public ResponseEntity<List<Home>> getAllHomesNoPage() {
        List<Home> homes = homeRepository.findAll();
        return ResponseEntity.ok(homes);
    }

    // 根据ID获取房产
    @GetMapping("/{id}")
    public ResponseEntity<?> getHomeById(@PathVariable Long id) {
        Optional<Home> home = homeRepository.findById(id);
        if (home.isPresent()) {
            return ResponseEntity.ok(home.get());
        } else {
            return ResponseEntity.notFound().build();
        }
    }

    // 创建房产
    @PostMapping
    public ResponseEntity<?> createHome(@RequestBody Home home) {
        // 验证楼栋是否存在
        if (home.getBuilding() != null && home.getBuilding().getId() != null) {
            Optional<Building> building = buildingRepository.findById(home.getBuilding().getId());
            if (!building.isPresent()) {
                return ResponseEntity.badRequest().body(new ApiResponse(false, "指定的楼栋不存在"));
            }
            home.setBuilding(building.get());
        }
        
        // 验证业主是否存在
        if (home.getOwner() != null && home.getOwner().getId() != null) {
            Optional<Owner> owner = ownerRepository.findById(home.getOwner().getId());
            if (!owner.isPresent()) {
                return ResponseEntity.badRequest().body(new ApiResponse(false, "指定的业主不存在"));
            }
            home.setOwner(owner.get());
        }
        
        Home savedHome = homeRepository.save(home);
        return ResponseEntity.ok(new ApiResponse(true, "房产创建成功", savedHome));
    }

    // 更新房产
    @PutMapping("/{id}")
    public ResponseEntity<?> updateHome(@PathVariable Long id, @RequestBody Home homeDetails) {
        Optional<Home> home = homeRepository.findById(id);
        if (home.isPresent()) {
            Home existingHome = home.get();
            
            // 验证楼栋是否存在
            if (homeDetails.getBuilding() != null && homeDetails.getBuilding().getId() != null) {
                Optional<Building> building = buildingRepository.findById(homeDetails.getBuilding().getId());
                if (!building.isPresent()) {
                    return ResponseEntity.badRequest().body(new ApiResponse(false, "指定的楼栋不存在"));
                }
                existingHome.setBuilding(building.get());
            }
            
            // 验证业主是否存在
            if (homeDetails.getOwner() != null && homeDetails.getOwner().getId() != null) {
                Optional<Owner> owner = ownerRepository.findById(homeDetails.getOwner().getId());
                if (!owner.isPresent()) {
                    return ResponseEntity.badRequest().body(new ApiResponse(false, "指定的业主不存在"));
                }
                existingHome.setOwner(owner.get());
            }
            
            existingHome.setName(homeDetails.getName());
            existingHome.setFloor(homeDetails.getFloor());
            existingHome.setArea(homeDetails.getArea());
            existingHome.setType(homeDetails.getType());
            existingHome.setStatus(homeDetails.getStatus());
            
            Home updatedHome = homeRepository.save(existingHome);
            return ResponseEntity.ok(new ApiResponse(true, "房产更新成功", updatedHome));
        } else {
            return ResponseEntity.notFound().build();
        }
    }

    // 删除房产
    @DeleteMapping("/{id}")
    public ResponseEntity<?> deleteHome(@PathVariable Long id) {
        Optional<Home> home = homeRepository.findById(id);
        if (home.isPresent()) {
            homeRepository.deleteById(id);
            return ResponseEntity.ok(new ApiResponse(true, "房产删除成功"));
        } else {
            return ResponseEntity.notFound().build();
        }
    }
    
    // 批量删除房产
    @DeleteMapping("/batch")
    public ResponseEntity<?> batchDeleteHomes(@RequestBody List<Long> ids) {
        homeRepository.deleteAllById(ids);
        return ResponseEntity.ok(new ApiResponse(true, "房产批量删除成功"));
    }
    
    // 根据楼栋ID获取房产
    @GetMapping("/building/{buildingId}")
    public ResponseEntity<List<Home>> getHomesByBuilding(@PathVariable Long buildingId) {
        Optional<Building> building = buildingRepository.findById(buildingId);
        if (!building.isPresent()) {
            return ResponseEntity.notFound().build();
        }
        List<Home> homes = homeRepository.findByBuildingId(buildingId);
        return ResponseEntity.ok(homes);
    }
    
    // 根据业主ID获取房产
    @GetMapping("/owner/{ownerId}")
    public ResponseEntity<List<HomeDTO>> getHomesByOwner(@PathVariable Long ownerId) {
        Optional<Owner> owner = ownerRepository.findById(ownerId);
        if (!owner.isPresent()) {
            return ResponseEntity.notFound().build();
        }
        List<Home> homes = homeRepository.findByOwnerId(ownerId);
        // 转换为DTO对象，包含建筑名称等信息
        List<HomeDTO> homeDTOs = DTOMapper.toHomeDTOList(homes);
        return ResponseEntity.ok(homeDTOs);
    }
    
    // 根据名称或状态搜索房产
    @GetMapping("/search")
    public ResponseEntity<List<Home>> searchHomes(@RequestParam(required = false) String name,
                                              @RequestParam(required = false) String status) {
        List<Home> homes;
        if (name != null && !name.isEmpty()) {
            homes = homeRepository.findByNameContaining(name);
        } else if (status != null && !status.isEmpty()) {
            homes = homeRepository.findByStatus(status);
        } else {
            homes = homeRepository.findAll();
        }
        return ResponseEntity.ok(homes);
    }
} 